<template>
  <div>
    <el-card>
      <el-input style="width:200px" @clear="searchCourse" clearable v-model="searchForm.courseName" placeholder="请输入课程名称" class="input-with-select">

      </el-input>
      <el-select style="width:200px" v-model="searchForm.courseType" placeholder="请选择课程类型">

        <li v-for="item in courseTypeList">
          <el-option :label="item.name" :value="item.code" />
        </li>
      </el-select>

      <el-button icon="Search" @click="searchCourse" />
      <el-button @click="resetCourse">重置</el-button>
      <el-button size="small" style="float: right"
                 @click="dialogFormVisible = true;isUpdate = false;imageKey++;">创建课程</el-button>
      <el-table :data="tableData" border style="width: 100%;margin-top:20px">
        <el-table-column prop="courseName" label="课程名称" width="400" />
        <el-table-column prop="courseType" label="课程类型" width="200" :formatter="formatType"/>
        <el-table-column prop="createdAt" label="课程上传时间" width="200" />
        <el-table-column label="操作" width="330">
          <template #default="scope">
            <el-button type="primary" size="small" @click="courseDetail(scope.row)">详情</el-button>
            <el-button type="danger" size="small" @click="deleteCourse(scope.row.courseId)">删除</el-button>
            <el-button type="primary" size="small" @click="openEdit(scope.row)">修改</el-button>
            <el-button type="primary" size="small" @click="courseExam(scope.row)">新增考试测验</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination style="margin-top:20px" :current-page="searchForm.pageNum" :page-size="searchForm.pageSize"
                     :page-sizes="[10, 20, 30, 40]" layout="->,total, sizes, prev, pager, next, jumper" :total="total"
                     @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <el-dialog v-model="dialogFormVisible" title="课程编辑" width="1000"  @close='closeDialog'>
      <el-form :model="courseForm">
        <el-form-item label="课程名称" :label-width="200">
          <el-input v-model="courseForm.courseName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="课程分类" :label-width="200">
            <el-select v-model="courseForm.courseType" placeholder="Please select a type">
              <li v-for="item in courseTypeList">
                <el-option :label="item.name" :value="item.code" />
              </li>
            </el-select>
        </el-form-item>
        <el-form-item label="课程图像：" :label-width="200">
          <el-upload
              class="avatar-uploader"
              :auto-upload = "false"
              :show-file-list="false"
              accept=".jpg,.png,.gif"
              :on-change="handleHeadIconChange"
          >
<!--            <el-avatar v-if="courseForm.courseImage" shape="square" :size="'large'" :key="imageKey" :src="courseForm.courseImage" />-->
            <el-image v-if="courseForm.courseImage" style="width: 256px; height: 144px" :key="imageKey" :src="courseForm.courseImage"/>
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="课程描述" :label-width="200">
          <el-input
              v-model="courseForm.description"
              style=""
              :autosize="{ minRows: 4, maxRows: 100 }"
              type="textarea"
              placeholder="Please input"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button v-if="!isUpdate" type="primary" @click="createCourse()">
            提交
          </el-button>
          <el-button v-if="isUpdate" @click="updateCourse()">
            修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>




<script setup>
import courseAPI from "../../api/course.js";
import {onBeforeMount, onBeforeUnmount, onMounted, reactive, ref} from "vue";
import {Plus} from "@element-plus/icons-vue";
import dictAPI from "../../api/dict.js";
import {ElMessage, ElMessageBox} from "element-plus";
import { useRouter } from 'vue-router'
const router = useRouter();
const dialogFormVisible = ref(false);
let isUpdate = ref(false);
let courseTypeList = ref(null);

//图像
const imageKey = ref(0);

// Dom 挂载之后
onMounted(() => {
  typeList();
  getCourseList();
})
// 课程数据
let tableData = ref([]);
let total = ref(0);
//课程详细数据
let detailData = ref({});
// 搜索条件
const searchForm = reactive({
  courseName:'',
  courseType:'',
  pageNum: 1,
  pageSize: 10,
})
//列表
let courseForm = reactive({
  courseId:'',
  courseName:'',
  courseType:'',
  description:'',
  courseImage:'',
  createdAt:'',
  createdBy:''
})
const getCourseList = async () => {
  const res = await courseAPI.page(searchForm);
  tableData.value = res.data.data.records;
  total.value = res.data.data.total;
}

//监听页的大小变化
const handleSizeChange = (size) => {
  searchForm.size = size;
  getCourseList();
}
//翻页
const handleCurrentChange = (current) => {
  searchForm.pageNum = current;
  getCourseList();
}

//查询
const searchCourse = () => {
  searchForm.pageNum = 1;
  getCourseList();
}
//重置
const resetCourse = () => {
  searchForm.courseName = '';
  searchForm.courseType = '';
  searchForm.pageNum = 1;
  getCourseList();
}

const closeDialog = () => {
  courseForm = reactive({})
}
//图像上传
const handleHeadIconChange =  (uploadedFile)=>{
  courseForm.courseImage = uploadedFile.raw;
  if (courseForm.courseImage) {
    const reader = new FileReader();
    reader.onload = function () {
      courseForm.courseImage = reader.result;//可以先在本地显示看看
    };
    reader.readAsDataURL(courseForm.courseImage);
  }
}

//获取课程类型字典值下拉框
const typeList = async () => {
  const res = await dictAPI.list({"dictionaryCode": 'COURSE_TYPE'});
  courseTypeList.value = JSON.parse(res.data.data[0].dictionaryValue);
}

//课程提交
const createCourse = async ()=>{
  const res = await courseAPI.add(courseForm);
  if (res.data.code === 200) {
    ElMessage({
      message: '添加成功',
      type: 'success',
    })
    dialogFormVisible.value = false;
    courseForm = reactive({})
    await getCourseList();
  }else {
    ElMessage.error(res.data.msg);
  }
}

const formatType = (type) => {
  for (let courseTypeListKey in courseTypeList.value) {
    if(courseTypeList.value[courseTypeListKey].code === type.courseType){
      return courseTypeList.value[courseTypeListKey].name;
    }
  }
}

//获取课程详细数据
const courseDetail =  (row) => {
  router.push({
    path:'/course/detail/'+Date.now(),
    query:{
      "courseId": row.courseId
    }
  });
}

//删除课程
const deleteCourse = (id) => {
  ElMessageBox.confirm(
      '确定要删除该课程信息吗?',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    const res = await courseAPI.delCourse({ 'courseId': id });
    if (res.data.code === 200) {
      ElMessage.success("删除成功")
      await getCourseList();
    } else {
      ElMessage.error("删除失败")
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除',
    })
  })
}

//修改课程
const updateCourse = async () => {
  const res = await courseAPI.update(courseForm);
  if (res.data.code === 200) {
    ElMessage({
      message: '修改成功',
      type: 'success',
    })
    dialogFormVisible.value = false;
    courseForm = reactive({})
    await getCourseList();
  }else {
    ElMessage.error(res.data.msg);
  }
}

//点击修改调取
const openEdit = (data) => {
  courseForm = data
  imageKey.value++;
  isUpdate.value = true;
  dialogFormVisible.value = true;
}

//跳转到新增考试测验
const courseExam =  (row) => {
  router.push({
    path:'/examination/exam',
    query:{
      "courseId": row.courseId
    }
  });
}
</script>


<style scoped>

</style>